const moment = require("moment");
const { type } = require("os");
const validate = require("validate.js");
// 自定义规则
validate.validators.classExits = function (value) {
  // return "cuowu";
};
validate.extend(validate.validators.datetime, {
  /**
   * 该函数自用用于日期格式转换
   * 他会在验证时自动转换, 数据转换为时间戳
   * 无法转换,返回NaN
   * @param value 要传入的值
   */
  parse(value, options) {
    let formats = ["YYYY-MM-DD HH:mm:ss", "YYYY-M-D H:m:s", "x"];
    if (options.dateOnly) {
      formats = ["YYYY-MM-DD", "YYYY-M-D", "X"];
    }
    return +moment.utc(value, formats, true);
  },
  /**
   * 用户显示错误消息是,使用的显示字符串
   * @param {*} value
   * @param {*} options
   */
  format(value, options) {
    let format = "YYYY-MM-DD";
    if (options.dateOnly) {
      format += " HH:mm:ss";
    }
    return moment.utc(value).format(format);
  },
});
const rule = {
  name: {
    presence: {
      allowEmpty: false,
    },
    type: "string",
    length: {
      is: 4,
    },
  },
  birthday: {
    presence: {
      allowEmpty: false,
    },
    datetime: {
      dateOnly: false,
      earliest: moment.utc().subtract(100, "y"),
      last: moment.utc().subtract(100, "y"),
    },
  },
  sex: {
    presence: true,
    type: "boolean",
    classExits: true,
  },
};
// 验证规则
const res = validate.validate(
  {
    name: "ssss",
    birthday: "2000-03-05 20:20:20",
    sex: false,
  },
  rule
);
console.log(res);
